//
//  WmcLocalAlbumVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/24.
//

import MJRefresh
import UIKit
import YPBedrock
import YPGraphicEngine

// MARK: - 扩展WmcLocalAlbumVC + WmcNavigatorProtocol

extension WmcLocalAlbumVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.localAlbum]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcLocalAlbumVM()
        if let viewModel = parms.context as? WmcLocalAlbumVM {
            vm = viewModel
        }
        let vc = WmcLocalAlbumVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcLocalAlbumVC + WmcVMProtocol

extension WmcLocalAlbumVC: WmcVMProtocol {
    typealias VMType = WmcLocalAlbumVM
}

// MARK: - 扩展WmcLocalAlbumVC + WmcAlbumTransitionProtocol

extension WmcLocalAlbumVC: WmcAlbumTransitionProtocol {}

// MARK: - [WmcLocalAlbumVC]

class WmcLocalAlbumVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        // 刷新数据
        viewModel.refreshData()
    }

    // Internal

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout.YP
            .CreateGridLayout(scrollDirection: .vertical,
                              minimumLineSpacing: 8,
                              minimumInteritemSpacing: 8,
                              sectionInset: Wmc_standardEdge.yp.set(top:0))
        return layout
    }()

    /// 列表显示
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView.YP.Create(layout: layout, delegate: self, dataSource: self, registers: [
            YPRegister(WmcLocalAlbumCell.self),
            YPRegister(WmcLocalAlbumSectionHeaderView.self, style: .header),
        ])
        // 下拉刷新
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.refreshData()
        })
        // 上拉加载
        collectionView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.loadMoreData()
        })
        return collectionView
    }()

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "选择照片"

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

    override func bindViewModel() {
        // 上拉下拉状态
        viewModel.bindRefreshState(to: collectionView)

        // 相册数据刷新
        viewModel.groupLocalMediaRelay.skip(1).subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            // 如果图片空，则返回
            if list.count <= 0 {
                weakSelf.backAction()
            } else {
                weakSelf.collectionView.reloadData()
            }
        }).disposed(by: rx.disposeBag)
    }
    
    override func backAction() {
        viewModel.backActionCall()
        super.backAction()
    }
}

// MARK: - UICollectionViewDelegate

extension WmcLocalAlbumVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let group = viewModel.groupLocalMediaRelay.value.yp.object(at: indexPath.section),
              let model = group.list.yp.object(at: indexPath.row),
              let cell = collectionView.cellForItem(at: indexPath) else { return }
        // 获取原图
        if let image = UIImage(contentsOfFile: model.previewImagePath) {
            // 使用转场动画
            let y = Self.NavHeight
            let height = Wmc_screenHeight - (y + WmcMediaBrowseVC.TooBarHeight)
            let endFrame = CGRect(x: 0, y: y,
                                  width: view.frame.width,
                                  height: height)
            transitionAnimation(startView: cell, image: image, endFrame: endFrame) { [weak self] in
                guard let weakSelf = self else { return }
                let browseVM = WmcMediaBrowseVM()
                browseVM.albumType = .local
                browseVM.mediaList = group.list.asWmcMediaList
                browseVM.dataSourceList = group.list
                browseVM.showIndex = indexPath.row
                browseVM.actionBlock = { type, index, vm in
                    let imageList = group.list
                    guard let dbImage = imageList.yp.object(at: index) else { return }
                    switch type {
                    case .delete:
                        vm.presentDeleteAlert {
                            guard let dbImage = group.list.yp.object(at: index) else { return }
                            WmcLocalMediaAlbumDBManager.deleteMedia(id: dbImage.id) { result in
                                if result {
                                    WmcHudManager.toast("删除成功")
                                    browseVM.remove(at: index)
                                    group.list.remove(at: index)
                                    if group.list.isEmpty {
                                        var temp = weakSelf.viewModel.groupLocalMediaRelay.value
                                        temp.remove(at: indexPath.section)
                                        if temp.isEmpty {
                                            if let viewControllers = weakSelf.navigationController?.viewControllers {
                                                var homeVC: UIViewController?
                                                for vc in viewControllers {
                                                    if vc is WmcHomeVC {
                                                        homeVC = vc
                                                        break
                                                    }
                                                }
                                                if let homeVC = homeVC {
                                                    weakSelf.navigationController?.popToViewController(homeVC, animated: true)
                                                    return
                                                }
                                            }
                                        }
                                        weakSelf.viewModel.groupLocalMediaRelay.accept(temp)
                                    }
                                    
                                    weakSelf.viewModel.backActionCall()
                                    collectionView.reloadData()
                                }
                            }
                        }
                    case .upload:
                        if WmcLoginManager.shared.isLogin {
                            syncAlertView()
                        } else {
                            WmcLoginManager.push(animated: true, success: {
                                syncAlertView()
                            })
                        }
                        
                        func syncAlertView() {
                            let syncSettingsView = WmcSyncSettingsView.showInView(style: .confirmType, isMustSelected: true)
                            syncSettingsView.ensureClosure = { list in
                                uploadTask()
                            }
                            weakSelf.view.addSubview(syncSettingsView)
                            
                            let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: syncSettingsView, contentLayoutBlock: { make in
                                make.left.right.bottom.equalToSuperview()
                                make.height.equalTo(373)
                            }))
                            presentVC.show()
                        }
                        
                        func uploadTask() {
                            WmcHudManager.toast("已上传")
                            
                            if let filePath = dbImage.mediaInfoType.relativePath,
                               let watermarkJson = dbImage.mediaInfoType.watermarkJson,
                               let jsonData: Data = watermarkJson.data(using: .utf8),
                               let watermarkInfoDic = try? JSONSerialization.jsonObject(with: jsonData, options: .fragmentsAllowed) as? [String: Any],
                               let media: WmcMedia = group.list.asWmcMediaList.yp.object(at: index)
                            {
                                let wmId = watermarkInfoDic["wmId"] as? Int
                                let takeTimeDic: [String: Any] = watermarkInfoDic["time"] as? [String: Any] ?? [:]
                                let takeTimestamp = takeTimeDic["time"] as? Double
                                let isNetTime = takeTimeDic["isNetTime"] as? Bool
                                var takeTimeDate = Date()
                                
                                if var takeTimestamp = takeTimestamp, isNetTime == true {
                                    takeTimestamp = takeTimestamp - 8 * 60 * 60
                                    takeTimeDate = Date(timeIntervalSince1970: takeTimestamp)
                                }
                                
                                let uploadParams = WmcMediaUploadResourceParameterModel()
                                if media is WmcImage { // 图片
                                    uploadParams.type = 0
                                    uploadParams.format = "png"
                                } else if media is WmcVideo { // 视频
                                    uploadParams.type = 1
                                    uploadParams.format = "mp4"
                                    if let path = dbImage.mediaInfoType.filePath {
                                        let videoTime = Int(AVAsset(url:path.yp.fileUrl).duration.seconds)
                                        uploadParams.videoTime = videoTime
                                    }
                                }
                                uploadParams.appId = 101 // 锁死水印相机appid
                                uploadParams.entryId = 1
                                uploadParams.wmcInfo = watermarkInfoDic
                                if let uid = WmcLoginManager.shared.yupaoAccountModel?.userId {
                                    uploadParams.uid = Int(uid)
                                }
                                uploadParams.wmId = wmId
                                uploadParams.takeTime = takeTimeDate.yp.string(.ymd_hms_iso8601, identifier: .asia(.Shanghai))
                                uploadParams.previewImagePath = dbImage.previewImagerelativePath
                                
                                WmcUploadQueueManager.appendUploadTask(path: filePath, model: uploadParams)
                            }
                        }
                    default: break
                    }
                }
                WmcNavigatorManager.push(.imageBrowse, style: .alpha, parms: browseVM)
            }
        }
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcLocalAlbumVC: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 40)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let lineCount: CGFloat = 3
        let lineSpacing = self.layout.minimumLineSpacing * (lineCount - 1)
        let horizontalEdge = self.layout.sectionInset.yp.horizontal
        let width = (collectionView.frame.size.width - lineSpacing - horizontalEdge) / lineCount - 1
        let height = width
        return CGSize(width: width, height: height)
    }
}

// MARK: - UICollectionViewDataSource

extension WmcLocalAlbumVC: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.groupLocalMediaRelay.value.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let group = viewModel.groupLocalMediaRelay.value.yp.object(at: section) {
            return group.list.count
        }
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headerView: WmcLocalAlbumSectionHeaderView = collectionView.yp.dequeueReusableView(.init(WmcLocalAlbumSectionHeaderView.self,
                                                                                                         style: .header),
                                                                                                   indexPath: indexPath)
            if let group = viewModel.groupLocalMediaRelay.value.yp.object(at: indexPath.section) {
                headerView.titleLabel.text = "\(group.title) [\(group.list.count)]"
            }
            return headerView
        } else {
            return .init()
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcLocalAlbumCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        if let group = viewModel.groupLocalMediaRelay.value.yp.object(at: indexPath.section),
           let model = group.list.yp.object(at: indexPath.row)
        {
            cell.configModel(model)
        }
        return cell
    }
}
